﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Leadtools.WinForms;
using Leadtools;
using Smallerp.Contracts.DataContracts;
using Leadtools.Codecs;
using SmallERP.COM;
using Leadtools.ImageProcessing;
using System.IO;

namespace SmallERP.PinBan
{
    public partial class FrmCutPic : Form
    {
        public FrmCutPic()
        {
            InitializeComponent();
            //InitClass();
        }
        RasterImageViewer _viewer = new RasterImageViewer();//显示操作等主要控件
        private RasterImage myImage;
        private RasterImage _Image// 当前处理的源图像
        {
            get { return myImage; }
            set
            {
                myImage = value;
                double w = Math.Min((double)_viewer.Width / value.Width, (double)_viewer.Height / value.Height);

                if (_viewer.InvokeRequired)
                {

                    this.Invoke(new SetScaleFactorHandl(SetCurrViewScaleFactor), new object[] { w });
                }
                else
                {
                    SetCurrViewScaleFactor(w);
                }

            }
        }
        private delegate void SetScaleFactorHandl(double scale);

        public List<PhotoInfo_PBDCT> _SrcPhotoList = new List<PhotoInfo_PBDCT>();//当前处理的原照片集合
        private PhotoInfo_PBDCT _SrcPhoto = new PhotoInfo_PBDCT();//当前处理原照片
        private List<PhotoInfo_PBDCT> _savePhotoList = new List<PhotoInfo_PBDCT>();
        RasterCodecs _codes;
        private int _XX = 0;//初始X值
        private int _YY = 0;//初始Y值
        private RasterRegionXForm _xform = new RasterRegionXForm();
        private bool _needZoom = false;
        private bool _isStart = true;
        //private double 0.16150551871330709

        public delegate int HandPhotoInfo(List<PhotoInfo_PBDCT> list);
        public event HandPhotoInfo SavePhotoToDB;
        private double _scaleFactor
        {
            get
            {
                if (_viewer != null)
                    return _viewer.ScaleFactor;
                else
                    return 0.16150551871330709;
            }
        }
        private void SetCurrViewScaleFactor(double inVlue)
        {
            //_viewer.ScaleFactor = inVlue * 0.9;
            if (_viewer.InvokeRequired)
            {
                this.Invoke(new SetScaleFactorHandl(SetCurrViewScaleFactor), new object[] { inVlue });
            }
            else
            {
                _viewer.ScaleFactor = inVlue * 0.9; ;

            }
        }
        private void label1_Click(object sender, EventArgs e)
        {

        }
        private void InitClass()
        {
            RasterCodecs.Startup();
            _codes = new RasterCodecs();
            //_viewer.Dock = DockStyle.Fill;
            _viewer.MouseWheel += new MouseEventHandler(_viewer_MouseWheel);
            _viewer.Dock = DockStyle.Fill;
            _viewer.AnimateRegion = true;
            _viewer.MouseMove += new MouseEventHandler(_viewer_MouseMove);
            _viewer.MouseDown += new MouseEventHandler(_viewer_MouseDown);
            _viewer.MouseUp += new MouseEventHandler(_viewer_MouseUp);
            _viewer.MouseDoubleClick += new MouseEventHandler(_viewer_MouseDoubleClick);
            //_viewer.SizeMode = RasterPaintSizeMode.Fit;
            _viewer.HorizontalAlignMode = RasterPaintAlignMode.Center;
            _viewer.VerticalAlignMode = RasterPaintAlignMode.Center;
            try
            {
                labelCurPicPath.Text = _SrcPhotoList.FirstOrDefault().PicPath;
                _Image = _codes.Load(_SrcPhotoList.FirstOrDefault().PicPath);
            }
            catch
            {

            }
            _viewer.Image = _Image;


            //txtWidth.Text = ((decimal)_Image.Width / _Image.XResolution).ToString("0.00");
            //txtHeigth.Text = ((decimal)_Image.Height / _Image.XResolution).ToString("0.00");
            //Rectangle rcPanel = Rectangle.Intersect(panelPicOper.PhysicalViewRectangle, panelPicOper.ClientRectangle); // get what you see in physical coordinates
            PointF centerPanel = new PointF(panelPicOper.Left + panelPicOper.Width / 2, panelPicOper.Top + panelPicOper.Height / 2); // get the c
            _viewer.CenterAtPoint(Point.Round(centerPanel));
            gridControlFileList.DataSource = _SrcPhotoList;
            panelPicOper.Controls.Add(_viewer);
            panelPicOper.Focus();
            comboBoxHorizontal.SelectedIndex = 0;
            comboBoxVertical.SelectedIndex = 0;
            comboBoxuUnit.SelectedIndex = 0;
            _xform.ViewPerspective = RasterViewPerspective.TopLeft;
            _xform.XOffset = 0;
            _xform.YOffset = 0;
            _xform.XScalarDenominator = 1;
            _xform.XScalarNumerator = 1;
            _xform.YScalarDenominator = 1;
            _xform.YScalarNumerator = 1;
            IniFile.FilePath = Application.StartupPath;
            string CutPicParastr = IniFile.IniReadValue("PB", "CutPicPara");
            if (string.IsNullOrEmpty(CutPicParastr))
            {
                IniFile.IniWriteValue("PB", "CutPicPara", "0,8,12,0,0@8x12英寸居中居中");
                CutPicParastr = "0,8,12,0,0@8x12英寸居中居中";
            }

            string[] GroupStr = CutPicParastr.Split('|');
            ResetcomboBoxModel(GroupStr);
            //SetValuesToForm(GroupStr[0].Split('@')[0]);
            _isStart = true;




        }

        void _viewer_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            CutPic();
        }
        private void SetValuesToForm(string defaultStr)
        {
            if (string.IsNullOrEmpty(defaultStr))
            {
                return;
            }
            if (defaultStr.Contains("-1"))
            {
                return;
            }
            string[] defaultCon = defaultStr.Split(',');
            comboBoxuUnit.SelectedIndex = Convert.ToInt16(defaultCon[0]);
            txtWidth.Text = defaultCon[1];
            txtHeigth.Text = defaultCon[2];
            comboBoxHorizontal.SelectedIndex = Convert.ToInt16(defaultCon[3]);
            comboBoxVertical.SelectedIndex = Convert.ToInt16(defaultCon[4]);
        }
        void _viewer_MouseUp(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Default;
        }

        void _viewer_MouseDown(object sender, MouseEventArgs e)
        {
            _XX = e.X;
            _YY = e.Y;
            _viewer.AnimateRegion = true;
        }

        void _viewer_MouseMove(object sender, MouseEventArgs e)
        {
            if (_Image.HasRegion && e.Button == MouseButtons.Left)
            {
                this.Cursor = Cursors.Hand;
                Rectangle rc = _Image.GetRegionBounds(null);
                int dx = (int)((e.X - _XX) / _scaleFactor);
                int dy = (int)((e.Y - _YY) / _scaleFactor);
                if ((rc.X + dx) <= 0)
                {
                    dx = -rc.X;
                }
                if (rc.Y + dy < 0)
                {
                    dy = -rc.Y;
                }
                if ((dy + rc.Height + rc.Y) >= _Image.Height)
                {
                    dy = _Image.Height - rc.Height - rc.Y;

                }
                if ((dx + rc.Width + rc.X) > _Image.Width)
                {
                    dx = _Image.Width - rc.Width - rc.X;
                }

                _Image.OffsetRegion(dy, dx);
                _XX = e.X;
                _YY = e.Y;

            }
        }

        void _viewer_MouseWheel(object sender, MouseEventArgs e)
        {
            Rectangle rc = Rectangle.Intersect(_viewer.PhysicalViewRectangle, _viewer.ClientRectangle); // get what you see in physical coordinates
            PointF center = new PointF(rc.Left + rc.Width / 2, rc.Top + rc.Height / 2); // get the center of what you see in physical coordinates
            Transformer t = new Transformer(_viewer.Transform);
            center = t.PointToLogical(center);
            double scaleFactor = _viewer.ScaleFactor;
            const float ratio = 1.2F;
            if (e.Delta > 0)
            {
                scaleFactor *= ratio;
            }
            else
            {
                scaleFactor /= ratio;
            }
            if (_viewer.ScaleFactor != scaleFactor)
            {
                _viewer.ScaleFactor = scaleFactor;

                // bring the original center into the view center
                t = new Transformer(_viewer.Transform);
                center = t.PointToPhysical(center); // get the center of what you saw before the zoom in physical coordinates
                _viewer.CenterAtPoint(Point.Round(center)); // bring the old center into the center of the view
            }

        }
        private void FrmCutPic_Load(object sender, EventArgs e)
        {
            InitClass();
            _isStart = false;
        }

        private void gridPhoto_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle == 0)
            {
                this.Cursor = Cursors.WaitCursor;
                try
                {
                    PhotoInfo_PBDCT ph = (PhotoInfo_PBDCT)gridPhoto.GetRow(e.RowHandle);
                    PhotoInfo_PBDCT phSave = _savePhotoList.FirstOrDefault(p => p.Photo_Base_Info.PhotoId == ph.Photo_Base_Info.PhotoId);
                    if (phSave != null)
                    {
                        _Image = _codes.Load(phSave.PicPath);
                    }
                    else
                    {
                        if (!File.Exists(ph.PicPath))
                        {
                            MessageBox.Show("文件不存在请删除该照片：" + ph.PicPath, "警告", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        _Image = _codes.Load(ph.PicPath);

                    }

                    _viewer.Image = _Image;
                    double w = Math.Min((double)_viewer.Width / _Image.Width, (double)_viewer.Height / _Image.Height);
                    _viewer.ScaleFactor = w * 0.9;

                    _SrcPhoto = ph;
                    labelCurPicPath.Text = ph.PicPath;
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                    _needZoom = false;
                }
            }
        }

        private void comboBoxuUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxuUnit.SelectedIndex == 0)
            {
                txtWidth.Text = ((decimal)_Image.Width / _Image.XResolution).ToString("0.00");
                txtHeigth.Text = ((decimal)_Image.Height / _Image.XResolution).ToString("0.00");
            }
            else
            {
                txtWidth.Text = ((decimal)_Image.Width / _Image.XResolution * (decimal)2.54).ToString("0.00");
                txtHeigth.Text = ((decimal)_Image.Height / _Image.XResolution * (decimal)2.54).ToString("0.00");
            }
            gridControlFileList.RefreshDataSource();
        }

        private void btnChangeSize_Click(object sender, EventArgs e)
        {
            string temp = txtWidth.Text;
            txtWidth.Text = txtHeigth.Text;
            txtHeigth.Text = temp;
        }

        private void simpleButtonCut_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                AddRectangleToRegion();


                string CutPicParastr = IniFile.IniReadValue("PB", "CutPicPara");
                string currComb = GetCombSet();
                if (CutPicParastr.Contains(currComb))
                {

                }
                else
                {
                    CutPicParastr = CutPicParastr + "|" + currComb;
                    IniFile.IniWriteValue("PB", "CutPicPara", CutPicParastr);
                    string[] GroupStr = CutPicParastr.Split('|');
                    ResetcomboBoxModel(GroupStr);
                    comboBoxModel.SelectedItem = currComb;
                }
            }
            catch (Exception ex)
            {

            }

            finally
            {
                this.Cursor = Cursors.Default;
            }

        }
        public delegate int GETCOMBSELECTINDEXHANDLE();
        public int GetUnitComboxSelectIndex()
        {
            if (comboBoxuUnit.InvokeRequired)
            {
               return  (int)this.Invoke(new GETCOMBSELECTINDEXHANDLE(GetUnitComboxSelectIndex));
            }else
            {
                return comboBoxuUnit.SelectedIndex;
            }


        }
        public int GetcomboBoxHorizontalSelectIndex()
        {
            if (comboBoxHorizontal.InvokeRequired)
            {
                return (int)this.Invoke(new GETCOMBSELECTINDEXHANDLE(GetcomboBoxHorizontalSelectIndex));
            }
            else
            {
                return comboBoxHorizontal.SelectedIndex;
            }


        }
        public int GetcomboBoxVerticalSelectIndex()
        {
            if (comboBoxVertical.InvokeRequired)
            {
                return (int)this.Invoke(new GETCOMBSELECTINDEXHANDLE(GetcomboBoxVerticalSelectIndex));
            }
            else
            {
                return comboBoxVertical.SelectedIndex;
            }


        }
        private void AddRectangleToRegion()
        {
            if (string.IsNullOrEmpty(txtWidth.Text) || string.IsNullOrEmpty(txtHeigth.Text) || _Image == null)
            {
                return;
            }
            ///获取参数
            Rectangle rc;
            decimal widthToInch = 0;//最终裁切尺寸
            decimal heightToInch = 0;
            decimal widthFactInch = (decimal)_Image.Width / _Image.XResolution;//实际尺寸
            decimal heightFactInch = (decimal)_Image.Height / _Image.YResolution;
            if (GetUnitComboxSelectIndex()== 0)
            {
                widthToInch = Convert.ToDecimal(txtWidth.Text);
                heightToInch = Convert.ToDecimal(txtHeigth.Text);
            }
            else
            {
                widthToInch = Convert.ToDecimal(txtWidth.Text) / (decimal)2.54;
                heightToInch = Convert.ToDecimal(txtHeigth.Text) / (decimal)2.54;
            }
            //计算缩放


            //decimal xScale = widthFactInch / widthToInch;
            //decimal yScale = heightFactInch / heightToInch;
            decimal tempMinWidth = widthToInch * heightFactInch / heightToInch;
            decimal tempMinHeigth = widthFactInch * heightToInch / widthToInch;
            if (tempMinWidth > widthFactInch)//以高为准计算宽宽不够那么只能宽为准计算高(宽不动计算最小需要的高)
            {
                heightToInch = tempMinHeigth;
                widthToInch = widthFactInch;
            }
            else if (tempMinWidth == widthFactInch)//等比缩放
            {
                heightToInch = heightFactInch;
                widthToInch = widthFactInch;
            }
            else
            {
                if (tempMinHeigth > heightFactInch)
                {
                    widthToInch = tempMinWidth;
                    heightToInch = heightFactInch;
                }
                else if (tempMinHeigth == heightFactInch)//等比缩放
                {
                    heightToInch = heightFactInch;
                    widthToInch = widthFactInch;
                }
                else
                {

                }
            }



            _needZoom = true;

            int HorizontalOffSet = 0;
            int VerticalOffset = 0;

            if (GetcomboBoxHorizontalSelectIndex() == 0)//左右居中位置
            {
                HorizontalOffSet = Convert.ToInt16(((widthFactInch - widthToInch) / 2) * _Image.XResolution);
            }
            else if (GetcomboBoxHorizontalSelectIndex() == 2)
            {
                HorizontalOffSet = Convert.ToInt16((widthFactInch - widthToInch) * _Image.XResolution);
            }
            else
            { }

            if (GetcomboBoxVerticalSelectIndex() == 0)
            {
                VerticalOffset = Convert.ToInt16(((heightFactInch - heightToInch) / 2) * _Image.XResolution);
            }
            else if (GetcomboBoxVerticalSelectIndex() == 2)
            {
                VerticalOffset = Convert.ToInt16((heightFactInch - heightToInch) * _Image.XResolution);

            }
            rc = new Rectangle(HorizontalOffSet, VerticalOffset, Convert.ToInt32(widthToInch * _Image.XResolution), Convert.ToInt32(heightToInch * _Image.XResolution));


            _Image.AddRectangleToRegion(_xform, rc, RasterRegionCombineMode.Set);
        }
        private void ResetcomboBoxModel(string[] GroupStr)
        {

            //comboBoxModel.Items.Clear();
            List<ComboxModel> list = new List<ComboxModel>();
            foreach (string str in GroupStr)
            {
                if (string.IsNullOrEmpty(str))
                {
                    continue;
                }
                if (str.Contains("-1"))
                {
                    continue;
                }
                string[] kvArray = str.Split('@');
                ComboxModel cm = new ComboxModel();
                cm.Key = kvArray[0];
                cm.Value = kvArray[1];
                list.Add(cm);
            }
            comboBoxModel.DataSource = list;
            comboBoxModel.DisplayMember = "Value";
            comboBoxModel.ValueMember = "Key";
        }
        private string GetCombSet()
        {
            //项目之间用“|”配置之间用“，”

            string strUnit = comboBoxuUnit.SelectedIndex.ToString();
            string ValueUnit = "";
            string ValueHorizontal = "";
            string ValueVertical = "";
            if (comboBoxuUnit.SelectedIndex == 0)
            {
                ValueUnit = "英寸";
            }
            else
            {
                ValueUnit = "厘米";

            }
            string strWidth = txtWidth.Text;
            string strHeight = txtHeigth.Text;
            string strHorizontal = comboBoxHorizontal.SelectedIndex.ToString();
            if (comboBoxHorizontal.SelectedIndex == 0)
            { ValueHorizontal = "居中"; }
            else if (comboBoxHorizontal.SelectedIndex == 1)
            {
                ValueHorizontal = "左对齐";

            }
            else { ValueHorizontal = "右对齐"; }
            string strVertical = comboBoxVertical.SelectedIndex.ToString();
            if (comboBoxVertical.SelectedIndex == 0)
            {
                ValueVertical = "居中";
            }
            else if (comboBoxVertical.SelectedIndex == 1)
            {
                ValueVertical = "上对齐";
            }
            else
            {
                ValueVertical = "下对齐";
            }
            string vauleStrSelect = strWidth + "x" + strHeight + ValueUnit + ValueHorizontal + ValueVertical;
            string SaveStrSelect = strUnit + "," + strWidth + "," + strHeight + "," + strHorizontal + "," + strVertical;
            return SaveStrSelect + "@" + vauleStrSelect;

        }

        private void comboBoxModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboxModel str = (ComboxModel)comboBoxModel.SelectedItem;
            SetValuesToForm(str.Key);
            ViewCut();
        }

        private void simpleButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                Rectangle rc = _Image.GetRegionBounds(null);

                IRasterCommand cropcommand = new CropCommand(rc);

                RasterImage img = _viewer.Image;
                img.XResolution = _Image.XResolution;
                img.XResolution = _Image.YResolution;
                cropcommand.Run(img);
                if (_needZoom)
                {
                    decimal goalWidthInch = 0;
                    decimal goalHeigthInch = 0;
                    if (comboBoxuUnit.SelectedIndex == 0)
                    {
                        goalWidthInch = Convert.ToDecimal(txtWidth.Text);
                        goalHeigthInch = Convert.ToDecimal(txtHeigth.Text);
                    }
                    else
                    {
                        goalWidthInch = Convert.ToDecimal(txtWidth.Text) / (decimal)2.54;
                        goalHeigthInch = Convert.ToDecimal(txtHeigth.Text) / (decimal)2.54;
                    }
                    SizeCommand SCommand = new SizeCommand();
                    SCommand.Width = Convert.ToInt16(goalWidthInch * _Image.XResolution);
                    SCommand.Height = Convert.ToInt16(goalHeigthInch * _Image.XResolution);
                    SCommand.Flags = RasterSizeFlags.Resample;
                    SCommand.Run(img);
                }
                _viewer.SizeMode = RasterPaintSizeMode.Normal;
                _codes.Save(img, @"D:\a.jpg", RasterImageFormat.Jpeg, 24);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

        }

        private void gridPhoto_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle >= 0)
            {
                this.Cursor = Cursors.WaitCursor;
                try
                {
                    PhotoInfo_PBDCT ph = (PhotoInfo_PBDCT)gridPhoto.GetRow(e.FocusedRowHandle);
                    PhotoInfo_PBDCT phSave = _savePhotoList.FirstOrDefault(p => p.Photo_Base_Info.PhotoId == ph.Photo_Base_Info.PhotoId);
                    if (phSave != null)
                    {
                        _Image = _codes.Load(phSave.PicPath);
                    }
                    else
                    {
                        if (!File.Exists(ph.PicPath))
                        {
                            MessageBox.Show("文件不存在请删除该照片：" + ph.PicPath, "警告", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        _Image = _codes.Load(ph.PicPath);

                    }

                    _viewer.Image = _Image;
                    double w = Math.Min((double)_viewer.Width / _Image.Width, (double)_viewer.Height / _Image.Height);
                    _viewer.ScaleFactor = w * 0.9;
                    //_viewer.ScaleFactor = 0.16150551871330709;
                    //if (comboBoxuUnit.SelectedIndex == 0)
                    //{
                    //    txtWidth.Text = ((decimal)_Image.Width / _Image.XResolution).ToString("0.00");
                    //    txtHeigth.Text = ((decimal)_Image.Height / _Image.XResolution).ToString("0.00");
                    //}
                    //else
                    //{
                    //    txtWidth.Text = ((decimal)_Image.Width / _Image.XResolution * (decimal)2.54).ToString("0.00");
                    //    txtHeigth.Text = ((decimal)_Image.Height / _Image.XResolution * (decimal)2.54).ToString("0.00");
                    //}
                    _SrcPhoto = ph;
                    labelCurPicPath.Text = ph.PicPath;
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                    _needZoom = false;
                }
            }
        }
        private  delegate object HandleGetValue();
        private RasterImageViewer GetImageViewer()
        {
            if (_viewer.InvokeRequired)
            {
                return (RasterImageViewer)this.Invoke(new HandleGetValue(GetImageViewer));
            }
            else
            {
                return _viewer;
            }
        }
        //裁切照片
        private void CutPic()
        {
            try
            {
                //this.Cursor = Cursors.WaitCursor;
                Rectangle rc = _Image.GetRegionBounds(null);

                IRasterCommand cropcommand = new CropCommand(rc);
                RasterImageViewer myView = GetImageViewer();
                RasterImage img = myView.Image;
                //img.XResolution = _Image.XResolution;
                //img.YResolution = _Image.YResolution;
                cropcommand.Run(img);
                if (_needZoom)
                {
                    decimal goalWidthInch = 0;
                    decimal goalHeigthInch = 0;
                    if (comboBoxuUnit.SelectedIndex == 0)
                    {
                        goalWidthInch = Convert.ToDecimal(txtWidth.Text);
                        goalHeigthInch = Convert.ToDecimal(txtHeigth.Text);
                    }
                    else
                    {
                        goalWidthInch = Convert.ToDecimal(txtWidth.Text) / (decimal)2.54;
                        goalHeigthInch = Convert.ToDecimal(txtHeigth.Text) / (decimal)2.54;
                    }
                    SizeCommand SCommand = new SizeCommand();
                    SCommand.Width = Convert.ToInt16(goalWidthInch * _Image.XResolution);
                    SCommand.Height = Convert.ToInt16(goalHeigthInch * _Image.XResolution);
                    SCommand.Flags = RasterSizeFlags.Resample;
                    SCommand.Run(img);
                }
                
                string savePath = _SrcPhoto.PicPath.Substring(0, _SrcPhoto.PicPath.LastIndexOf('.')) + "_cut.jpg";
                PhotoInfo_PBDCT photo = new PhotoInfo_PBDCT();
                photo.PhotoId = _SrcPhoto.PhotoId;
                ;
                photo.Photo_Base_Info = new PhotoDCT() { PhotoId = _SrcPhoto.PhotoId, PixHeight = img.Height, PixWidth = img.Width, DPI = img.XResolution, PicPath = savePath, PhotoName = _SrcPhoto.Photo_Base_Info.PhotoName, Width = (double)img.Width / img.XResolution, Height = (double)img.Height / img.YResolution };
                if (_savePhotoList.FirstOrDefault(p => p.Photo_Base_Info.PhotoId == photo.Photo_Base_Info.PhotoId) == null)
                {
                    _savePhotoList.Add(photo);
                }
                if (File.Exists(savePath))
                {
                    File.Delete(savePath);
                }
                _codes.Save(img, savePath, RasterImageFormat.Jpeg, 24);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                //this.Cursor = Cursors.Default;
            }
        }
        //预览照片
        private void ViewCut()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                AddRectangleToRegion();
                RecordSelect();


            }
            catch (Exception ex)
            {

            }

            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private void RecordSelect()
        {
            string CutPicParastr = IniFile.IniReadValue("PB", "CutPicPara");
            string currComb = GetCombSet();
            if (CutPicParastr.Contains(currComb))
            {

            }
            else
            {
                CutPicParastr = CutPicParastr + "|" + currComb;
                IniFile.IniWriteValue("PB", "CutPicPara", CutPicParastr);
                string[] GroupStr = CutPicParastr.Split('|');
                ResetcomboBoxModel(GroupStr);
                comboBoxModel.SelectedItem = currComb;
            }
        }
        private void simpleButtonView_Click(object sender, EventArgs e)
        {
            AddRectangleToRegion();
        }

        private void simpleButtonAllCut_Click(object sender, EventArgs e)
        {
            //backgroundWorkerCutPic.RunWorkerAsync();
            foreach (PhotoInfo_PBDCT ph in _SrcPhotoList)
            {
                if (_savePhotoList.FirstOrDefault(p => p.Photo_Base_Info.PhotoId == ph.Photo_Base_Info.PhotoId) == null)
                {
                    _SrcPhoto = ph;
                    _Image = _codes.Load(ph.PicPath);

                    SetImageToView(_Image);
                    double w = Math.Min((double)_viewer.Width / _Image.Width, (double)_viewer.Height / _Image.Height);
                    SetCurrViewScaleFactor(w);
                    AddRectangleToRegion();
                    CutPic();

                    //_needZoom = false
                }
            }
        }

        private void txtHeigth_KeyDown(object sender, KeyEventArgs e)
        {
            if (!_isStart && e.KeyCode == Keys.Enter)
            {
                AddRectangleToRegion();
            }
        }

        private void comboBoxHorizontal_SelectedIndexChanged(object sender, EventArgs e)
        {

            AddRectangleToRegion();
        }

        private void comboBoxVertical_SelectedIndexChanged(object sender, EventArgs e)
        {

            AddRectangleToRegion();
        }

        private void simpleButtonCutPic_Click(object sender, EventArgs e)
        {

            if (!_Image.HasRegion)
            {
                AddRectangleToRegion();
            }
            CutPic();
            RecordSelect();
            gridControlFileList.RefreshDataSource();
        }

        private void comboBoxHorizontal_Click(object sender, EventArgs e)
        {
            AddRectangleToRegion();
        }

        private void txtHeigth_Click(object sender, EventArgs e)
        {
            AddRectangleToRegion();
        }

        private void comboBoxVertical_Click(object sender, EventArgs e)
        {
            AddRectangleToRegion();
        }

        private void comboBoxModel_Click(object sender, EventArgs e)
        {
            _isStart = false;
        }

        private void simpleButtonBack_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {

                PhotoInfo_PBDCT ph = _SrcPhoto;
                PhotoInfo_PBDCT src = _SrcPhotoList.FirstOrDefault(p => p.Photo_Base_Info.PhotoId == ph.Photo_Base_Info.PhotoId);
                PhotoInfo_PBDCT delPh = _savePhotoList.FirstOrDefault(p => p.Photo_Base_Info.PhotoId == ph.Photo_Base_Info.PhotoId);
                if (delPh != null)
                {
                    File.Delete(delPh.Photo_Base_Info.PicPath);
                    _savePhotoList.Remove(delPh);
                }
                _SrcPhoto = src;
                _Image = _codes.Load(src.PicPath);
                _viewer.Image = _Image;
                double w = Math.Min((double)_viewer.Width / _Image.Width, (double)_viewer.Height / _Image.Height);
                _viewer.ScaleFactor = w * 0.9;

                _SrcPhoto = ph;
                labelCurPicPath.Text = ph.PicPath;
                gridControlFileList.RefreshDataSource();
            }
            finally
            {
                this.Cursor = Cursors.Default;
                _needZoom = false;
            }
        }

        private void gridPhoto_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                if (e.Column.Name == "gridColumn2")
                {
                    PhotoInfo_PBDCT pbdc = (PhotoInfo_PBDCT)gridPhoto.GetRow(e.RowHandle);
                    var phSave = _savePhotoList.FirstOrDefault(p => p.Photo_Base_Info.PhotoId == pbdc.Photo_Base_Info.PhotoId);
                    if (phSave != null)
                    {
                        string sizeInch = ((decimal)phSave.Photo_Base_Info.PixWidth / phSave.Photo_Base_Info.DPI).ToString("0.00") + "x" + ((decimal)phSave.Photo_Base_Info.PixHeight / phSave.Photo_Base_Info.DPI).ToString("0.00");
                        string sizeCm = (phSave.Photo_Base_Info.PixWidth / phSave.Photo_Base_Info.DPI * 2.54).ToString("0.00") + "x" + (phSave.Photo_Base_Info.PixHeight / phSave.Photo_Base_Info.DPI * 2.54).ToString("0.00");
                        if (comboBoxuUnit.SelectedIndex == 0)
                        {
                            e.DisplayText = sizeInch;
                        }
                        else
                        {
                            e.DisplayText = sizeCm;
                        }
                    }
                    else
                    {
                        if (comboBoxuUnit.SelectedIndex == 0)
                        { }
                        else
                        {
                            e.DisplayText = pbdc.PhotoSizeCm;
                        }
                    }
                }

            }
        }

        private void simpleButtonSaveTodb_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否保存裁切数据，保存请点击“确定”，不保存请点击“取消”", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
               int aaa= SavePhotoToDB(_savePhotoList);
               if (aaa == 0)
               {
                   this.Close();
               }
            }
        }
        delegate void SetImageToViewHander(RasterImage inImage);
        private void SetImageToView(RasterImage inImage)
        {
            if (_viewer.InvokeRequired)
            {
                this.Invoke(new SetImageToViewHander(SetImageToView), new object[] { inImage });
            }
            else
            {
                _viewer.Image = inImage;
            }

        }
        //delegate void SetImageToViewHander(RasterImage inImage);
        private void SetScaleFactor(double inFactor)
        {
            if (_viewer.InvokeRequired)
            {
                this.Invoke(new SetScaleFactorHandl(SetScaleFactor), new object[] { inFactor });
            }
            else
            {
                _viewer.ScaleFactor = inFactor * 0.9; ;
                
            }
        }
        private void backgroundWorkerCutPic_DoWork(object sender, DoWorkEventArgs e)
        {
            ////foreach (PhotoInfo_PBDCT ph in _SrcPhotoList)
            ////{
            ////    if (_savePhotoList.FirstOrDefault(p => p.Photo_Base_Info.PhotoId == ph.Photo_Base_Info.PhotoId) == null)
            ////    {
            ////        _SrcPhoto = ph;
            ////        _Image = _codes.Load(ph.PicPath);

            ////        SetImageToView(_Image);
            ////        double w = Math.Min((double)_viewer.Width / _Image.Width, (double)_viewer.Height / _Image.Height);
            ////        SetCurrViewScaleFactor(w);
            ////        AddRectangleToRegion();
            ////        CutPic();

            ////        //_needZoom = false
            ////    }
            ////}
           
        }
        
        private void backgroundWorkerCutPic_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            gridControlFileList.RefreshDataSource();
        }



    }
    public class ComboxModel
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }
}
